import { Particle, Position } from '../types/game';
import { GAME_CONFIG } from '../config/fruits';
import confetti from 'canvas-confetti';

export class AnimationSystem {
  private particles: Particle[] = [];
  private canvas: HTMLCanvasElement | null = null;
  private ctx: CanvasRenderingContext2D | null = null;
  private animationId: number | null = null;

  constructor() {
    try {
      console.log('开始创建动画系统...');
      this.createCanvas();
      this.startAnimation();
      console.log('动画系统创建成功');
    } catch (error) {
      console.error('动画系统创建失败:', error);
    }
  }

  // 创建粒子画布
  private createCanvas(): void {
    this.canvas = document.createElement('canvas');
    this.canvas.width = GAME_CONFIG.CONTAINER_WIDTH;
    this.canvas.height = GAME_CONFIG.CONTAINER_HEIGHT;
    this.canvas.style.position = 'absolute';
    this.canvas.style.top = '0';
    this.canvas.style.left = '0';
    this.canvas.style.pointerEvents = 'none';
    this.canvas.style.zIndex = '10';
    
    this.ctx = this.canvas.getContext('2d');
  }

  // 获取粒子画布
  public getCanvas(): HTMLCanvasElement | null {
    return this.canvas;
  }

  // 创建合成特效
  public createMergeEffect(position: Position, color: string, size: number): void {
    // 创建粒子爆炸效果
    for (let i = 0; i < GAME_CONFIG.PARTICLE_COUNT; i++) {
      const angle = (Math.PI * 2 * i) / GAME_CONFIG.PARTICLE_COUNT;
      const speed = 2 + Math.random() * 4;
      
      const particle: Particle = {
        id: `particle_${Date.now()}_${i}`,
        x: position.x,
        y: position.y,
        vx: Math.cos(angle) * speed,
        vy: Math.sin(angle) * speed - 2, // 向上的初始速度
        color: this.getRandomColor(color),
        size: Math.random() * size * 0.3 + 5,
        life: GAME_CONFIG.PARTICLE_LIFE,
        maxLife: GAME_CONFIG.PARTICLE_LIFE
      };
      
      this.particles.push(particle);
    }

    // 播放五彩纸屑效果
    this.playConfetti(position);
  }

  // 播放五彩纸屑效果
  private playConfetti(position: Position): void {
    const rect = this.canvas?.getBoundingClientRect();
    if (!rect) return;

    confetti({
      particleCount: 30,
      spread: 60,
      origin: {
        x: position.x / GAME_CONFIG.CONTAINER_WIDTH,
        y: position.y / GAME_CONFIG.CONTAINER_HEIGHT
      },
      colors: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7', '#fd79a8']
    });
  }

  // 获取随机颜色变体
  private getRandomColor(baseColor: string): string {
    const colors = [
      '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', 
      '#ffeaa7', '#fd79a8', '#a29bfe', '#6c5ce7'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  }

  // 创建投放特效
  public createDropEffect(position: Position, color: string): void {
    // 创建投放波纹效果
    for (let i = 0; i < 8; i++) {
      const angle = (Math.PI * 2 * i) / 8;
      const speed = 1 + Math.random();
      
      const particle: Particle = {
        id: `drop_${Date.now()}_${i}`,
        x: position.x,
        y: position.y,
        vx: Math.cos(angle) * speed,
        vy: Math.sin(angle) * speed,
        color: color,
        size: Math.random() * 3 + 2,
        life: 500,
        maxLife: 500
      };
      
      this.particles.push(particle);
    }
  }

  // 创建得分特效
  public createScoreEffect(position: Position, score: number): void {
    // 创建得分文字元素
    const scoreElement = document.createElement('div');
    scoreElement.textContent = `+${score}`;
    scoreElement.style.position = 'absolute';
    scoreElement.style.left = `${position.x}px`;
    scoreElement.style.top = `${position.y}px`;
    scoreElement.style.color = '#ff6b6b';
    scoreElement.style.fontSize = '20px';
    scoreElement.style.fontWeight = 'bold';
    scoreElement.style.pointerEvents = 'none';
    scoreElement.style.zIndex = '20';
    scoreElement.style.textShadow = '2px 2px 4px rgba(0,0,0,0.3)';
    scoreElement.style.transform = 'translate(-50%, -50%)';
    
    // 添加到DOM
    document.body.appendChild(scoreElement);
    
    // 动画效果
    scoreElement.animate([
      { 
        opacity: '1', 
        transform: 'translate(-50%, -50%) scale(1)',
        color: '#ff6b6b'
      },
      { 
        opacity: '1', 
        transform: 'translate(-50%, -70px) scale(1.2)',
        color: '#4ecdc4'
      },
      { 
        opacity: '0', 
        transform: 'translate(-50%, -100px) scale(0.8)',
        color: '#45b7d1'
      }
    ], {
      duration: 1000,
      easing: 'ease-out'
    }).onfinish = () => {
      document.body.removeChild(scoreElement);
    };
  }

  // 更新粒子系统
  private updateParticles(): void {
    this.particles = this.particles.filter(particle => {
      // 更新粒子位置
      particle.x += particle.vx;
      particle.y += particle.vy;
      particle.vy += 0.1; // 重力影响
      
      // 更新生命值
      particle.life -= 16; // 假设60FPS
      
      return particle.life > 0;
    });
  }

  // 渲染粒子
  private renderParticles(): void {
    if (!this.ctx || !this.canvas) return;
    
    // 清除画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 渲染所有粒子
    this.particles.forEach(particle => {
      if (!this.ctx) return;
      
      const alpha = particle.life / particle.maxLife;
      this.ctx.save();
      this.ctx.globalAlpha = alpha;
      this.ctx.fillStyle = particle.color;
      this.ctx.beginPath();
      this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
      this.ctx.fill();
      this.ctx.restore();
    });
  }

  // 开始动画循环
  private startAnimation(): void {
    const animate = () => {
      this.updateParticles();
      this.renderParticles();
      this.animationId = requestAnimationFrame(animate);
    };
    animate();
  }

  // 创建背景渐变动画
  public animateBackground(element: HTMLElement, colors: string[]): void {
    const keyframes = colors.map((color, index) => ({
      background: `linear-gradient(135deg, ${color}, ${colors[(index + 1) % colors.length]})`
    }));

    element.animate(keyframes, {
      duration: 5000,
      iterations: Infinity,
      direction: 'alternate'
    });
  }

  // 创建按钮按压动画
  public animateButton(button: HTMLElement): void {
    button.animate([
      { transform: 'scale(1)' },
      { transform: 'scale(0.95)' },
      { transform: 'scale(1)' }
    ], {
      duration: 150,
      easing: 'ease-in-out'
    });
  }

  // 创建游戏结束动画
  public createGameOverEffect(): void {
    // 屏幕震动效果
    if (this.canvas) {
      this.canvas.animate([
        { transform: 'translateX(0)' },
        { transform: 'translateX(-5px)' },
        { transform: 'translateX(5px)' },
        { transform: 'translateX(-3px)' },
        { transform: 'translateX(3px)' },
        { transform: 'translateX(0)' }
      ], {
        duration: 500,
        easing: 'ease-in-out'
      });
    }

    // 红色粒子爆炸
    for (let i = 0; i < 50; i++) {
      const particle: Particle = {
        id: `gameover_${Date.now()}_${i}`,
        x: Math.random() * GAME_CONFIG.CONTAINER_WIDTH,
        y: Math.random() * GAME_CONFIG.CONTAINER_HEIGHT * 0.3,
        vx: (Math.random() - 0.5) * 10,
        vy: Math.random() * 5 + 2,
        color: '#ff6b6b',
        size: Math.random() * 8 + 3,
        life: 2000,
        maxLife: 2000
      };
      
      this.particles.push(particle);
    }
  }

  // 销毁动画系统
  public destroy(): void {
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
    
    if (this.canvas && this.canvas.parentNode) {
      this.canvas.parentNode.removeChild(this.canvas);
    }
  }
}